package com.zmn.plat.admin.controller.common.area;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.dictionary.DictModel;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.model.entity.area.BaseArea;
import com.zmn.plat.services.interfaces.area.BaseAreaService;
import com.zmn.plat.services.interfaces.company.BaseCompanyAreaService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author nowind
 * @since 17/11/10 11:48
 */
@Controller
@RequestMapping("/common/area/")
public class CommonAreaController extends PlatBaseController {

    @Resource
    private BaseAreaService areaService;
    @Resource
    BaseCompanyAreaService companyAreaService;

    /**
     * region 区域联动
     *
     * @param response
     * @param parentId
     */
    @RequestMapping(value = "listChilds")
    public void listChilds(HttpServletResponse response, @RequestParam(value = "parentId", defaultValue = "1") int parentId) {

        if (parentId == 0) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }

        List<BaseArea> items = areaService.listByParentId(parentId);

        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";

        for (int i = 0; i < items.size(); i++) {
            BaseArea item = items.get(i);
            String name = item.getName();
            sb.append(String.format(jsonFormat, items.get(i).getAreaId(), name, (i == items.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }

    /**
     * region 区域联动
     *
     * @param response
     * @param parentId
     */
    @RequestMapping(value = "listVtDtoChilds")
    public void listVtDtoChilds(HttpServletResponse response, @RequestParam(value = "parentId", defaultValue = "1") int parentId) {

        if (parentId == 0) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }

        List<BaseArea> items = areaService.listByParentId(parentId);

        List<DictModel> result = Lists.newArrayList();
        for (int i = 0; i < items.size(); i++) {
            BaseArea item = items.get(i);
            String name = item.getName();
            result.add(new DictModel(item.getAreaId(), name));
        }
        ResponseUtil.outWrite(response, JSON.toJSONString(result));

    }

}
